import { useUserStore } from "@/store/user";
import api from "@/api/api";
import { showCaptcha } from "@/utils/captcha";

export async function guard(to) {
    const userStore = useUserStore();
    // 不需要用户信息的页面，或已经拿到用户信息，直接通过
    if (!to.meta.needUser || userStore.user) {
        return true;
    }

    // 获取用户信息
    let res = await api.userInfo({ uid: to.query.uid });
    // 成功
    if (res.status == 200) {
        userStore.setUser(res.data);
        return true;
    }
    if(res.status == 403) {
        alert("当前权限不足");
        return false;
    }

    // 未登录或登录失效，弹出验证码
    await showCaptcha(async (verifyParam: string, resolve) => {
        let uid = localStorage.getItem("uid");
        let res = await api.userVisitorLogin({ uid, verifyParam });
        // 登录成功
        if (res.status == 200) {
            userStore.setUser(res.data);
            localStorage.setItem("uid", res.data.uid);
            resolve();
        }
        
        return res.status == 200;
    });
    return true;
}
